package Z11_3_ReentrantLock;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author： pang-yun
 * @date： 2021-11-04 13:24
 * 功能目的 ：用于
 */


public class DeadLockDemo {
    public static void main(String[] args) {
        ChopsLick a = new ChopsLick("1");
        ChopsLick b = new ChopsLick("2");
        ChopsLick c = new ChopsLick("3");
        ChopsLick d = new ChopsLick("4");
        ChopsLick e = new ChopsLick("5");

        new Philosophy("AA", a, b).start();
        new Philosophy("BB", b, c).start();
        new Philosophy("CC", c, d).start();
        new Philosophy("DD", d, e).start();
        new Philosophy("EE", e, a).start();
    }

}


@Slf4j
@Data
@AllArgsConstructor
class Philosophy extends Thread {

    ChopsLick left;
    ChopsLick right;

    public Philosophy(String name, ChopsLick left, ChopsLick right) {
        super(name);
        this.left = left;
        this.right = right;
    }

    @Override
    public void run() {
        while (true) {
            if (left.tryLock()) {
                try {
                    if (right.tryLock()) {
                        try {
                            eat();
                        } finally {
                            right.unlock();
                        }
                    }
                } finally {
                    left.unlock();
                }
            }
        }
    }

    public void eat() {
        log.info("eat!");
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

@Data
@AllArgsConstructor
class ChopsLick extends ReentrantLock {
    private String name;
}
